#!/bin/bash

set -o errexit
set -o nounset
set -o pipefail

# cd to the repo root
REPO_ROOT=$(git rev-parse --show-toplevel)
cd "${REPO_ROOT}"

if [ -z "${GIT_REF:-}" ]; then
  echo "GIT_REF must be set"
  exit 1
fi

if [[ -z "${REGISTRY_BASE:-}" ]]; then
  echo "REGISTRY_BASE must be set"
  exit 1
fi

if [[ ! "${GIT_REF}" =~ ^refs/heads/.* ]]; then
  echo "GIT_REF=${GIT_REF} is not of the expected format refs/heads/*"
  exit 1
fi

BRANCH=${GIT_REF/refs\/heads\//}
echo "BRANCH is ${BRANCH}"

GIT_REVISION=$(git rev-parse --short HEAD)
echo "GIT_REVISION is ${GIT_REVISION}"

export IMAGE_TAG="g${GIT_REVISION}"
echo "IMAGE_TAG is ${IMAGE_TAG}"

pushd ${REPO_ROOT}/guestbook-go
VERSION=${IMAGE_TAG} REGISTRY=${REGISTRY_BASE} make push
popd